package com.hxm.demo.test1;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2022/10/25 14:01:04
 */
public class TestRemoveNthFromEnd {

    /**
     * 19. 删除链表的倒数第 N 个结点
     *
     * @param args
     */
    public static void main(String[] args) {

    }

    /**
     * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
     *
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode tail = new ListNode(0, head);
        ListNode slow = tail;
        ListNode fast = head;
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return tail.next;
    }
}
